package com.yb.guigu.pick.auth.service.impl;

import com.yb.guigu.pick.auth.bean.dto.response.SysMenuDTO;
import com.yb.guigu.pick.auth.entity.SysMenu;
import com.yb.guigu.pick.auth.mapper.SysMenuMapper;
import com.yb.guigu.pick.core.bean.GuiguResult;
import com.yb.guigu.pick.auth.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 姚兵
 * @since 2023-05-30
 */
@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public GuiguResult getUserMenu(Long userId) {

        List<SysMenu> menus = this.list();
        List<SysMenuDTO> sysMenuDTOS=new ArrayList<>(menus.size());
        menus.forEach(sysMenu -> {
            SysMenuDTO sysMenuDTO = new SysMenuDTO();
            BeanUtils.copyProperties(sysMenu,sysMenuDTO);
            sysMenuDTOS.add(sysMenuDTO);
        });

        //封装dto对象到 children里面
        return GuiguResult.success(treeify(sysMenuDTOS));
    }

    @Override
    public GuiguResult menuAll() {
        List<SysMenu> menus = this.list();
        List<SysMenuDTO> sysMenuDTOS=new ArrayList<>(menus.size());
        menus.forEach(sysMenu -> {
            SysMenuDTO sysMenuDTO = new SysMenuDTO();
            BeanUtils.copyProperties(sysMenu,sysMenuDTO);
            sysMenuDTOS.add(sysMenuDTO);
        });

        //封装dto对象到 children里面
        return GuiguResult.success(treeify(sysMenuDTOS));
    }

    private List<SysMenuDTO>  treeify(List<SysMenuDTO> sysMenuDTOS){

        Map<Integer, List<SysMenuDTO>> parentIdMap = sysMenuDTOS.stream().filter(Objects::nonNull)
                .filter(item -> !item.getParentId().equals(0))
                .collect(Collectors.groupingBy(SysMenuDTO::getParentId));
        log.info("{}",parentIdMap);
        sysMenuDTOS.forEach(item->{
            List<SysMenuDTO> childList = parentIdMap.get(item.getId());
            if(Objects.nonNull(childList))
                item.setChildren(childList);
        });
        log.info("treeVos:{}",sysMenuDTOS);
        List<SysMenuDTO> collect = sysMenuDTOS.stream().filter(item -> item.getParentId().equals(0)).collect(Collectors.toList());
        log.info("collect:{}",collect);
        return collect;
    }
}
